<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\goods\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Cache;
use think\Db;
use app\goods\model\GoodsClass as GoodsClassModel;
use app\goods\model\GoodsType as GoodsTypeModel;
use app\goods\model\Unit as UnitModel;
use app\goods\model\Attr as AttrModel;
use app\goods\model\AttrVal as AttrValModel;
use app\goods\model\Style as StyleModel;
use app\goods\model\Tag as TagModel;

/**
 * 商品款类
 * @package app\admin\controller
 */
class Category extends Admin
{
    /**
    *商品款类列表
    */
    public function index(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $order = $this->getOrder('sort ASC,classid DESC');
        $map = $this->getMap();
        $data_list = GoodsClassModel::getAll($map,$order);       
        return ZBuilder::make('table')
        ->setSearch(['classname' =>'名称'])
        ->addOrder('sort,classid')
        ->addColumns([ // 批量添加列
            ['artno', '货号'],
            ['classname', '名称'],
            ['top', '置顶', 'switch'],
            ['status', '状态', 'status'],
            ['right_button', '操作', 'btn']           
        ])
        ->addRightButton('edit', ['href' => url('show',['id' => '__ID__']), 'icon' => 'fa fa-fw fa-crosshairs', 'title' => '查看'], true)
        ->setTableName('goods_class')
        ->setPrimaryKey('classid')
        ->addRightButton('edit')
        ->addTopButton('add')
        ->addRightButton('delete')
        ->setRowList($data_list)
        ->fetch();
    }



    


    /**
    *新增
    */
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['hide'] == 1){
                if(empty($data['typeid'])){
                    $this->error('请选择所属分类');
                }

                if(empty($data['styleid'])){
                    $this->error('请选择所属类型');
                }

                //单位列表
                $unit_list = UnitModel::where(array('status' => '1'))->column('unitid,unitname');

                //标签列表
                $tag_list  = TagModel::where('status', '1')->column('tagid,tagname');
                $params = [];
                $params = [['text', 'classname', '款类名称'],
                        ['text', 'customcode', '自编码'],
                        ['text', 'artno', '货号'],
                        ['text', 'supplierno', '供应商编码'],
                        ['text', 'craft', '工艺'], 
                        ['text', 'texture', '材质'],
                        ['text', 'accounting', '核算属性'],
                        ['select', 'minunit', '最小单位', '', $unit_list],
                        ['select', 'maxunit', '最大单位', '', $unit_list],               
                        ['text', 'sort', '排序'],
                        ['radio', 'top' , '置顶', '', ['0' => '否' ,'1' => '是'], '0'],
                        ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '1'],
                        ['image', 'thumb', '图片'],
                        ['select','carrelation','关联款','','','','ajax multiple','',['url'=>url('elseclass'),'datakey'=>'id','dataname'=>'name']],
                        ['select', 'tagid','标签', '', $tag_list, '', 'multiple'],
                        ['hidden', 'typeid', $data['typeid']],
                        ['hidden', 'hide', '2'],
                        ['hidden', 'parentid', $data['parentid']],
                        ['hidden', 'styleid', $data['styleid']],
                        ];
                //属性
                $attr_str = StyleModel::where('styleid',$data['styleid'])->column('attrid');
                if($attr_str){
                    $attr_str             = trim($attr_str['0'],',');
                    $attr_where['attrid'] = array('in',$attr_str);
                    $attr_data            = AttrModel::where($attr_where)->select();
                    foreach ($attr_data as $key => $value) {
                        $detail_list = [];
                        switch ($value['inittype']) {
                            case '1':
                                $params[] = ['text',$value['attrid'],$value['attrname']];
                                break;
                            case '2':
                                $params[] = ['image',$value['attrid'],$value['attrname']];
                                break;
                            case '3':
                                $detail_list = explode(',', $value['typedetail']);
                                $detail_list = array_flip($detail_list);
                                foreach ($detail_list as $k => $val) {
                                    $detail_list[$k] = $k;
                                }

                                $params[] = ['select',$value['attrid'],$value['attrname'],'',$detail_list];
                                break;
                            case '4':
                                $detail_list = explode(',', $value['typedetail']);
                                $detail_list = array_flip($detail_list);
                                foreach ($detail_list as $k => $val) {
                                    $detail_list[$k] = $k;
                                }

                                $params[] = ['radio',$value['attrid'],$value['attrname'],'',$detail_list];
                                break;
                            case '5':
                                $detail_list = explode(',', $value['typedetail']);
                                $detail_list = array_flip($detail_list);
                                foreach ($detail_list as $k => $val) {
                                    $detail_list[$k] = $k;
                                }
                                $params[] = ['checkbox',$value['attrid'],$value['attrname'],'',$detail_list];
                                break;
                        }
                    }
                }

            
                $lays = [];
                foreach ($params as $key => $value) {
                    $lays = $lays + [$value['1'] => 3];
                }
                $lays['carrelation'] = 6;
                $params[] = ['ueditor', 'info'];
                
                return ZBuilder::make('form')
                    ->addFormItems($params)
                    ->layout($lays)
                    ->setPageTitle('【Step2】填写详情')
                    ->fetch();
            }else{
                $attr_val  = [];
                $data_list = [];
                $data_list['carrelation'] = [];
                foreach ($data as $key => $value) {
                    if((int)($key)>0){
                        $attr_val  += [$key => $value];
                    }else{
                        $data_list += [$key => $value];
                    }
                }
                if(isset($data['carrelation'])){
                    $data_list['carrelation']=','.implode($data['carrelation'], ',').',';
                }else{
                    $data_list['carrelation']='';
                }

                if(isset($data['tagid'])){
                    $data_list['tagid']=','.implode($data['tagid'], ',').',';
                }else{
                    $data_list['tagid']='';
                }
                $classid = GoodsClassModel::insertGetId($data_list);
                if($classid){
                    foreach ($attr_val as $key => $value) {
                        $attr_str = '';
                        if(is_array($value)){
                            foreach ($value as $k => $val) {
                                $attr_str .=$val.',';
                            }
                            $attr_str = ','.$attr_str;
                            $result   = AttrValModel::insert(['attrid' => $key, 'classid' => $classid, 'detail' => $attr_str]);
                        }else{
                            $result = AttrValModel::insert(['attrid' => $key, 'classid' => $classid, 'detail' => $value]);
                        }
                    }
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            }

        }

        //顶级分类
        $type_list = GoodsTypeModel::where(array('status' => '1', 'parentid' => 0))->order('sort')->column('typeid,classname');
        
        $style_list = StyleModel::where('status', '1')->column('styleid,stylename');
        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列            
            ['hidden', 'hide', '1'],
            ['linkage', 'parentid', '顶级分类', '<span class="text-danger">必须</span>', $type_list, '', url('get_type'), 'typeid'],
            ['select', 'typeid', '所属分类', '<span class="text-danger">必须</span>'],
            ['select', 'styleid', '所属类型', '<span class="text-danger">必须</span>', $style_list],
            
        ])
        ->setPageTitle('【Step1】选择分类')
        ->isAjax(false)
        ->layout(['parentid' => 4, 'typeid' => 4, 'styleid' => 4])
        ->fetch();
    }


    /**
    *修改
    */
    public function edit($id = 0){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $info = Db::name('goods_class')->where('classid',$data['classid'])->find();
            if($data['hide'] == 1){
                if(empty($data['typeid'])){
                    $this->error('请选择所属分类');
                }

                if(empty($data['styleid'])){
                    $this->error('请选择所属类型');
                }
                $info['styleid']  = $data['styleid'];
                $info['parentid'] = $data['parentid'];
                (array)$info['typeid']   = $data['typeid'];
                $info +=AttrValModel::where('classid',$info['classid'])->column('attrid,detail');

                //已关联款
                $classwhere['classid'] = array('in',$info['carrelation']);
                $else_class = GoodsClassModel::where($classwhere)->column('classid,artno');

                //标签列表
                $tag_list  = TagModel::where('status', '1')->column('tagid,tagname');


                //单位列表
                $unit_list = UnitModel::where(array('status' => '1'))->column('unitid,unitname');
                $params = [];
                $params = [['text', 'classname', '款类名称'],
                        ['text', 'customcode', '自编码'],
                        ['text', 'artno', '货号'],
                        ['text', 'supplierno', '供应商编码'],
                        ['text', 'craft', '工艺'], 
                        ['text', 'texture', '材质'],
                        ['text', 'accounting', '核算属性'],
                        ['select', 'minunit', '最小单位', '', $unit_list],
                        ['select', 'maxunit', '最大单位', '', $unit_list],               
                        ['text', 'sort', '排序'],
                        ['radio', 'top' , '置顶', '', ['0' => '否' ,'1' => '是'], '0'],
                        ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '1'],
                        ['image', 'thumb', '图片'],
                        ['select','carrelation','关联款','',$else_class,'','ajax multiple','',['url'=>url('elseclass'),'datakey'=>'id','dataname'=>'name']],
                        ['select', 'tagid','标签', '', $tag_list, '', 'multiple'],
                        ['hidden', 'typeid', $data['typeid']],
                        ['hidden', 'hide', '2'],
                        ['hidden', 'parentid', $data['parentid']],
                        ['hidden', 'classid'],
                        ['hidden', 'styleid', $data['styleid']],
                        ];
                //属性
                $attr_str = StyleModel::where('styleid',$data['styleid'])->column('attrid');
                if($attr_str){
                    $attr_str             = trim($attr_str['0'],',');
                    $attr_where['attrid'] = array('in',$attr_str);
                    $attr_data            = AttrModel::where($attr_where)->select();
                    foreach ($attr_data as $key => $value) {
                        $detail_list = [];
                        switch ($value['inittype']) {
                            case '1':
                                $params[] = ['text',$value['attrid'],$value['attrname']];
                                break;
                            case '2':
                                $params[] = ['image',$value['attrid'],$value['attrname']];
                                break;
                            case '3':
                                $detail_list = explode(',', $value['typedetail']);
                                $detail_list = array_flip($detail_list);
                                foreach ($detail_list as $k => $val) {
                                    $detail_list[$k] = $k;
                                }

                                $params[] = ['select',$value['attrid'],$value['attrname'],'',$detail_list];
                                break;
                            case '4':
                                $detail_list = explode(',', $value['typedetail']);
                                $detail_list = array_flip($detail_list);
                                foreach ($detail_list as $k => $val) {
                                    $detail_list[$k] = $k;
                                }

                                $params[] = ['radio',$value['attrid'],$value['attrname'],'',$detail_list];
                                break;
                            case '5':
                                $detail_list = explode(',', $value['typedetail']);
                                $detail_list = array_flip($detail_list);
                                foreach ($detail_list as $k => $val) {
                                    $detail_list[$k] = $k;
                                }
                                $params[] = ['checkbox',$value['attrid'],$value['attrname'],'',$detail_list];
                                break;
                        }
                    }
                }

            
                $lays = [];
                foreach ($params as $key => $value) {
                    $lays = $lays + [$value['1'] => 3];
                }
                $lays['carrelation'] = 6;
                $params[] = ['ueditor', 'info'];
                
                return ZBuilder::make('form')
                    ->addFormItems($params)
                    ->layout($lays)
                    ->setPageTitle('【Step2】填写详情')
                    ->setFormData($info)
                    ->fetch();
            }else{
                $attr_val  = [];
                $data_list = [];
                $data_list['carrelation'] = [];
                foreach ($data as $key => $value) {
                    if((int)($key)>0){
                        $attr_val  += [$key => $value];
                    }else{
                        $data_list += [$key => $value];
                    }
                }
                if(isset($data['carrelation'])){
                    $data_list['carrelation']=','.implode($data['carrelation'], ',').',';
                }else{
                    $data_list['carrelation']='';
                }

                if(isset($data['tagid'])){
                    $data_list['tagid']=','.implode($data['tagid'], ',').',';
                }else{
                    $data_list['tagid']='';
                }
                
                $result = GoodsClassModel::update($data_list);
                
                    $classid = $info['classid'];
                    AttrValModel::where('classid',$classid)->delete();
                    foreach ($attr_val as $key => $value) {
                        $attr_str = '';
                        if(is_array($value)){
                            foreach ($value as $k => $val) {
                                $attr_str .=$val.',';
                            }
                            $attr_str = ','.$attr_str;
                            $res   = AttrValModel::insert(['attrid' => $key, 'classid' => $classid, 'detail' => $attr_str]);
                        }else{
                            $res = AttrValModel::insert(['attrid' => $key, 'classid' => $classid, 'detail' => $value]);
                        }
                    }
                if($result || $res){
                    $this->success('修改成功', cookie('__forward__'));
                }else{
                    $this->error('无修改', cookie('__forward__'));
                }
            }

        }

        $id = input('id');
        //详情
        $info = GoodsClassModel::where('classid',$id)->find();

        //顶级分类
        $type_list = GoodsTypeModel::where(array('status' => '1', 'parentid' => 0))->order('sort')->column('typeid,classname');

        //子分类
        $child_list = GoodsTypeModel::where(array('status' => '1', 'parentid' => $info['parentid']))->column('typeid,classname');

        //类型
        $style_list = StyleModel::where('status','1')->column('styleid,stylename');

        //JS
        $js = <<<EOF
            <script type="text/javascript">
                $(function(){
                    var s = 1;
                    $('select[name=styleid]').change(function(){
                        if(s == 1){
                        alert('改变类型可能会丢失部分属性');
                        s = 2;
                    }

                    })
                });
            </script>
EOF;

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列            
            ['hidden', 'hide', '1'],
            ['hidden', 'classid'],
            ['linkage', 'parentid', '顶级分类', '<span class="text-danger">必须</span>', $type_list, '', url('get_type'), 'typeid'],
            ['select', 'typeid', '所属分类', '<span class="text-danger">必须</span>', $child_list],
            ['select', 'styleid', '所属类型', '<span class="text-danger">必须</span>', $style_list],
            
        ])
        ->setFormData($info)
        ->setPageTitle('【Step1】选择分类')
        ->isAjax(false)
        ->layout(['parentid' => 4, 'typeid' => 4, 'styleid' => 4])
        ->setExtraJs($js)
        ->fetch();
    }




    /**
    *删除
    */
    public function delete($record = []){
        $data   = input('ids');
        $result = GoodsClassModel::where(array('classid' => $data))->delete();
        if($result){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
    *获取子类type
    */
    public function get_type(){
        $id = input('parentid');
        $data = GoodsTypeModel::where(array('status' => '1','parentid' => $id))->column('typeid,classname');
        $list = [];
        foreach ($data as $key => $value) {
            $list[]=['key' => $key, 'value' => $value];
        }
        $data_list['list'] = $list;
        $data_list['code'] = '1'; //判断状态
        $data_list['msg']  = '请求成功'; //回传信息
        return json($data_list);
    }

    public function show($id = 0){
        $info                = Db::name('goods_class')->where('classid', $id)->find();
        $info['parentid']    = GoodsTypeModel::where('typeid', $info['parentid'])->value('classname');
        $info['typeid']      = GoodsTypeModel::where('typeid', $info['typeid'])->value('classname');
        $info['styleid']     = StyleModel::where('styleid', $info['styleid'])->value('stylename');
        $info['minunit']     = UnitModel::where('unitid', $info['minunit'])->value('unitname');
        $info['maxunit']     = UnitModel::where('unitid', $info['maxunit'])->value('unitname');
        if($info['top'] == '1'){
            $info['top'] = '已置顶';
        }else{
            $info['top'] = '未置顶';
        }
        if($info['status'] == '1'){
            $info['status'] = '启用';
        }else{
            $info['status'] = '禁用';
        }
        $params = [];
        $params = [
                    ['static', 'classid', 'ID'],
                    ['static', 'parentid', '顶级分类'],
                    ['static', 'typeid', '所属分类'],
                    ['static', 'styleid', '类型'],
                    ['static', 'classname', '款类名称'],
                    ['static', 'customcode', '自编码'],
                    ['static', 'artno', '货号'],
                    ['static', 'supplierno', '供应商编码'],
                    ['static', 'craft', '工艺'], 
                    ['static', 'texture', '材质'],
                    ['static', 'minunit', '最小单位'],
                    ['static', 'maxunit', '最大单位'],
                    ['static', 'accounting', '核算属性'],               
                    ['static', 'sort', '排序'],
                    ['static', 'top' , '置顶状态'],
                    ['static', 'status' , '启用状态'],
                    ['image', 'thumb', '图片'],
                ];

        $attr_val = AttrValModel::where('classid', $info['classid'])->select();
        if(!empty($attr_val)){
            foreach ($attr_val as $key => $value) {
                $attrname     = AttrModel::where('attrid', $value['attrid'])->value('attrname');
                $inittype     = AttrModel::where('attrid', $value['attrid'])->value('inittype');
                if($inittype == 2){
                    $params[] = ['image', $value['attrid'], $attrname];
                }else{
                    $params[] = ['static', $value['attrid'], $attrname];
                }
                $arr  = [$value['attrid'] => $value['detail']];
                $info = $info + $arr;
            }
        }
        foreach ($params as $key => $value) {
            if($value['0'] == 'image'){
                array_push($params, $value);
                unset($params[$key]);
            }
        }
        $lays = [];
        foreach ($params as $key => $value) {
            $lays = $lays + [$value['1'] => 3];
        }
        $params[] = ['ueditor', 'Info'];
                
        return ZBuilder::make('form')
            ->addFormItems($params)
            ->layout($lays)
            ->setPageTitle('查看详情')
            ->setFormData($info)
            ->hideBtn('submit')
            ->fetch();
    }

    /**
    *查找款号
    */
    public function elseclass(){
        $search=input('q');
        $where['artno']   =['like',"%$search%"];
        $where['status'] = 1;
        $class=GoodsClassModel::field('classid,artno')->where($where)->select();
        $class_list=[];
        $a= 0;
        foreach($class as $value){
            $b = $a++;
            $key=$value['classid'];
            $class_list[$b]['id']=$key;
            $class_list[$b]['name']=$value['artno'];
        }
        return json(['items'=>$class_list,'total_count'=>sizeof($class_list)]);
    }

   
}
